import urllib
import urllib2
import re
import cookielib
import xml.etree.ElementTree as et
import getpass

global debug

def init(init_debug):
	global debug
	debug=init_debug
	cj=cookielib.CookieJar()
	cj.clear()
	CHandler = urllib2.HTTPCookieProcessor(cj)
	browser = urllib2.build_opener(CHandler)
	browser.addheaders = [('User-agent', 'Remote XML Client')]
	urllib2.install_opener(browser)

def login(gateway):
	for i in range(3):	
		username = raw_input("Enter your remote account: ")
		password = getpass.getpass()
		if post_login(username,password,gateway):
			break
		elif i<2:
			print "Wrong Credentials! Try again " + str(2-i)
			continue
		else:
			sys.exit()

def send_xml(data,gateway):
	response=send_request(gateway+"/cgi-bin/webapp", data)
	if debug == 1 : print response
	tree = et.fromstring(response)
	webapp= tree.findall("./webapp")
	keys = tree.findall("./*/key")
	values = tree.findall("./*/value")
	result={}
	if len(webapp) > 0 and webapp[0].tag == "webapp" and  keys[0].text == "error" and values[0].text == "1":
		print "You have been logged out. Please type login to login again!"
		sys.exit()
 	for item in range(len(keys)):
        	result[keys[item].text]=values[item].text
	return result

def send_post(url,data):
	data=urllib.urlencode(data)
	return send_request(url, data)

def send_request(url,data='',rtr=1):
	try:
		req = urllib2.Request(url, data)
		response = urllib2.urlopen(req )
	except:
		print "Connection Problem"
		print "Retrying :" + str(rtr)
		if rtr <3 :
			send_request(url,data,rtr+1)
		else:
			print "Check ip connection to your gateway !"
			exit()
	return response.read()

def post_login(username,password,gateway):
	data = {'user' : username ,'password' : password,}
	resp = send_post(gateway+"/cgi-bin/login",data)
	redirect=re.findall("url=(.*?)\"",resp)
	if len(redirect)==1 and redirect[0] =="/main.html" :
		status=1
	else:
		status=0	
	return status

